import router from "./router.js";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "../store";
NProgress.configure({
  ease: "ease",
  speed: 500,
});

const writeNames = [
  "/login",
  "/all",
  "/cold",
  "/stomach",
  "/skin",
  "/detail",
  "/news",
];
router.beforeEach((to, from, next) => {
  NProgress.start();
  if (to.matched.length == 0) {
    next("/404");
  }
  if (localStorage.getItem("token")) {
    let commonUse = JSON.parse(sessionStorage.getItem("commonUse"));
    if (commonUse == undefined) {
      sessionStorage.setItem("commonUse", JSON.stringify([to]));
    } else {
      let flag = true;
      commonUse.forEach((item) => {
        if (item.path === to.path) {
          flag = false;
        }
      });
      if (flag) {
        commonUse.push(to);
      }
      sessionStorage.setItem("commonUse", JSON.stringify(commonUse));
    }
    let type = JSON.parse(JSON.parse(localStorage.getItem("user")).user.UserInfo.UserInfo).userType
    if (to.path === "/login" || to.path === "/main") {
      if(type === '1'){
        next("/home");
      }else{
        next('/userhome')
      }
    }
    return next();
  } else {
    if (writeNames.includes(to.path)) {
      next();
    } else {
      next("/login");
    }
  }
});

router.afterEach((transition) => {
  NProgress.done();
});

export default router;
